package com.aprivate.kn.ratingsystem.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.aprivate.kn.ratingsystem.FileUtil;
import com.aprivate.kn.ratingsystem.R;
import com.aprivate.kn.ratingsystem.adapter.ImageAdapter;
import com.aprivate.kn.ratingsystem.adapter.QuestionAdapter;
import com.aprivate.kn.ratingsystem.adapter.RatingAdapter;
import com.aprivate.kn.ratingsystem.adapter.RatingClassAdapter;
import com.aprivate.kn.ratingsystem.bean.QuestionListBean;
import com.aprivate.kn.ratingsystem.bean.RatingQuestionBean;
import com.aprivate.kn.ratingsystem.daoBean.Answer;
import com.aprivate.kn.ratingsystem.daoBean.Elements;
import com.aprivate.kn.ratingsystem.daoBean.ProductInfo;
import com.aprivate.kn.ratingsystem.daoBean.Topics;
import com.aprivate.kn.ratingsystem.daoutil.AnswerDaoUtil;
import com.aprivate.kn.ratingsystem.daoutil.ElementDaoUtil;
import com.aprivate.kn.ratingsystem.daoutil.ProductInfoDaoUtil;
import com.aprivate.kn.ratingsystem.daoutil.TopicsDaoUtil;
import com.aprivate.kn.ratingsystem.view.HorizontalListView;
import com.aprivate.kn.ratingsystem.viewUtil.ToastUtil;
import com.codingending.popuplayput.PopupDialog;
import com.codingending.popuplayput.PopupLayout;
import com.example.customcarcount.IChangeCoutCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by kenan on 2018/11/30.
 */

public class RatingActivity extends Activity implements EasyPermissions.PermissionCallbacks {
    private EditText et_ratingName;
    private Button btn_save;
    private ImageView img_back;
    private String productInfoId;
    private ProductInfoDaoUtil productInfoDaoUtil;
    private ElementDaoUtil elementDaoUtil;
    private TopicsDaoUtil topicsDaoUtil;
    private AnswerDaoUtil answerDaoUtil;
    private ProductInfo productInfo;
    private List<Elements> elementsList;
    private List<Topics> topicsList;
    private LayoutInflater inflater;
    private ArrayList<Answer> answerList;
    private String editor;
    private List<Answer> answerOldList;
    private List<String> mImageList;


    private static int REQUEST_CAMERA = 100;
    private static int REQUEST_TAKE_PHOTO_PERMISSION = 101;
    private String currentTopIcId = "";
    private String currentFileName = "";
    private File photoFile;
    private ImageAdapter mImageAdapter;
    private GridView imageGridView;
    private List<Answer> answers;
    private PopupLayout popupLayout;

    private Button btnQuestion;
    private DrawerLayout mDrawlayout;
    private View mLayoutQuestion;
    private ListView mAnswerList;
    private ListView mUnAnswerList;
    private Button mAnswerButton;
    private Button mUnAnswerButton;
    private List<QuestionListBean> mAnswerListData = new ArrayList<>();
    private List<QuestionListBean> mUnAnswerListData = new ArrayList<>();
    private QuestionAdapter mAnswerAdapter;
    private QuestionAdapter mUnAnswerAdapter;

    private ListView mQuestionListView;
    private RatingAdapter mRatingAdapter;
    private HorizontalListView mFirstClass, mSecondClass, mThirdClass;
    private RatingClassAdapter mFirstClassAdapter;
    private RatingClassAdapter mSecondClassAdapter;
    private RatingClassAdapter mThirdClassAdapter;
    private List<Elements> mOneElementList;
    private List<Elements> mTwoElementList;
    private List<Elements> mThirdElementList;
    private List<RatingQuestionBean> mQuestionList;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_protect_rating);
        mFirstClass = findViewById(R.id.first_class);
        mSecondClass = findViewById(R.id.second_class);
        mThirdClass = findViewById(R.id.third_class);

        mQuestionListView = findViewById(R.id.questionnaire_listview);
        et_ratingName = findViewById(R.id.et_ratingName);
        btn_save = findViewById(R.id.btn_save);
        img_back = findViewById(R.id.img_back);
        inflater = LayoutInflater.from(this);
        btnQuestion = findViewById(R.id.btn_question);
        mDrawlayout = findViewById(R.id.draw_layout);
        mLayoutQuestion = findViewById(R.id.layout_question);
        mAnswerButton = findViewById(R.id.answer_question);
        mUnAnswerButton = findViewById(R.id.un_answer_question);
        mAnswerList = findViewById(R.id.answer_list);
        mUnAnswerList = findViewById(R.id.un_answer_list);
        productInfoId = getIntent().getStringExtra("productionid");
        answerList = new ArrayList<>();
        initQuestion();
        initDataFromDB();
        onClickListener();

    }

    private void initQuestion() {
        ViewGroup.LayoutParams layoutParams = mLayoutQuestion.getLayoutParams();
        layoutParams.width = (int) (this.getWindowManager().getDefaultDisplay().getWidth() * 0.75);
        layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
        mLayoutQuestion.setLayoutParams(layoutParams);

        mAnswerList.setVisibility(View.VISIBLE);
        mUnAnswerList.setVisibility(View.GONE);
    }

    private void onClickListener() {
        mFirstClass.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (TextUtils.isEmpty(et_ratingName.getText())) {
                    Toast.makeText(RatingActivity.this, "请输入测评人", Toast.LENGTH_SHORT).show();
                    return;
                }
                mFirstClassAdapter.setCurrentItem(i);
                getTwoElements(mOneElementList.get(i));
                getQuestionList();
            }
        });

        mSecondClass.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (TextUtils.isEmpty(et_ratingName.getText())) {
                    Toast.makeText(RatingActivity.this, "请输入测评人", Toast.LENGTH_SHORT).show();
                    return;
                }
                mSecondClassAdapter.setCurrentItem(i);
//                getQuestionElements(mTwoElementList.get(i));
                getThirdElements(mTwoElementList.get(i));
                getQuestionList();
            }
        });

        mThirdClass.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (TextUtils.isEmpty(et_ratingName.getText())) {
                    Toast.makeText(RatingActivity.this, "请输入测评人", Toast.LENGTH_SHORT).show();
                    return;
                }
                mThirdClassAdapter.setCurrentItem(i);
                getQuestionElements(mThirdElementList.get(i));
                getQuestionList();
            }
        });
        mRatingAdapter.setOnViewHolder(new RatingAdapter.OnViewHolder() {
            @Override
            public void setQustionDataToView(RatingAdapter.ViewHolder viewHolder, int position,
                                             RatingQuestionBean bean) {
                showQuestionItem(position + 1, viewHolder, bean);
            }
        });
        mDrawlayout.setDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                getQuestionList();
            }

            @Override
            public void onDrawerOpened(View drawerView) {
            }

            @Override
            public void onDrawerClosed(View drawerView) {

            }

            @Override
            public void onDrawerStateChanged(int newState) {
            }
        });

        btnQuestion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mDrawlayout.isDrawerOpen(mLayoutQuestion)) {
                    mDrawlayout.closeDrawer(mLayoutQuestion);
                } else {
                    mDrawlayout.openDrawer(mLayoutQuestion);
                }
            }
        });

        mUnAnswerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mUnAnswerButton.setTextColor(ContextCompat.getColor(RatingActivity.this,R.color.white));
                mAnswerButton.setTextColor(ContextCompat.getColor(RatingActivity.this,R.color.background_gradient_start));
                mAnswerList.setVisibility(View.GONE);
                mUnAnswerList.setVisibility(View.VISIBLE);
            }
        });

        mAnswerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAnswerButton.setTextColor(ContextCompat.getColor(RatingActivity.this,R.color.white));
                mUnAnswerButton.setTextColor(ContextCompat.getColor(RatingActivity.this,R.color.background_gradient_start));
                mAnswerList.setVisibility(View.VISIBLE);
                mUnAnswerList.setVisibility(View.GONE);
            }
        });
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RatingActivity.this.finish();
            }
        });
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(et_ratingName.getText().toString())) {
                    if (answerList != null && answerList.size() > 0) {
                        answerDaoUtil.insertListAnswer(answerList);
                    }
                    if (productInfo != null) {
                        productInfoDaoUtil.insertProductInfo(productInfo);
                    }
                    finish();
                } else {
                    ToastUtil.showLongToast(RatingActivity.this, "请填写测评人");
                }
            }
        });
        et_ratingName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                editor = editable.toString();
                if (!TextUtils.isEmpty(editor)) {
                    for (int i = 0; i < mQuestionList.size(); i++) {
                        Topics topics = mQuestionList.get(i).getTopics();
                        topics.setEditor(editor);
                        String topicId = topics.getId();
                        Answer answer = findAnswer(topicId);
                        answer.setEditor(editor);
                    }
                }
            }
        });
        mAnswerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                QuestionListBean questionListBean = mAnswerListData.get(i);
                mQuestionListView.setSelection(questionListBean.getQuestionPosition());
                mDrawlayout.closeDrawer(mLayoutQuestion);
            }
        });
        mUnAnswerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                QuestionListBean questionListBean = mUnAnswerListData.get(i);

                mQuestionListView.setSelection(questionListBean.getQuestionPosition());
                mDrawlayout.closeDrawer(mLayoutQuestion);
            }
        });
    }

    private void initDataFromDB() {
        // 获取项目基本信息
        productInfoDaoUtil = new ProductInfoDaoUtil(this);
        productInfo = productInfoDaoUtil.queryUserById(Long.valueOf(productInfoId));
        // 获取要素基本信息
        elementDaoUtil = new ElementDaoUtil(this);

        elementsList = elementDaoUtil.queryElmentsByQueryBuilder(productInfoId);
        // 获取问卷信息 项目id
        topicsDaoUtil = new TopicsDaoUtil(this);
        topicsList = topicsDaoUtil.queryTopicrByQueryBuilder(productInfoId);
        //初始化answerDaoUtil
        answerDaoUtil = new AnswerDaoUtil(this);
        answerOldList = new ArrayList<>();
        answerOldList.addAll(answerDaoUtil.queryElmentsByQueryBuilder(productInfoId));

        mImageList = new ArrayList<>();

        //ratingClass设置
        mOneElementList = new ArrayList<>();
        mTwoElementList = new ArrayList<>();
        mThirdElementList = new ArrayList<>();
        mFirstClassAdapter = new RatingClassAdapter(this, mOneElementList);
        mSecondClassAdapter = new RatingClassAdapter(this, mTwoElementList);
        mThirdClassAdapter = new RatingClassAdapter(this, mThirdElementList);
        mFirstClass.setAdapter(mFirstClassAdapter);
        mSecondClass.setAdapter(mSecondClassAdapter);
        mThirdClass.setAdapter(mThirdClassAdapter);

        mQuestionList = new ArrayList<>();
        mRatingAdapter = new RatingAdapter(this, mQuestionList);
        mQuestionListView.setAdapter(mRatingAdapter);

        getFirstElements();
        if (null != elementsList && elementsList.size() > 0) {
            if (mOneElementList.size() > 0) {
                mFirstClass.setSelection(0);
                getTwoElements(elementsList.get(0));
                if (mTwoElementList.size() > 0) {
                    mSecondClass.setSelection(0);
                    getThirdElements(mTwoElementList.get(0));
                    if (mTwoElementList.size() > 0) {
                        mThirdClass.setSelection(0);
                    }
                }
            }
        }

        mAnswerAdapter = new QuestionAdapter(this, mAnswerListData);
        mUnAnswerAdapter = new QuestionAdapter(this, mUnAnswerListData);
        mAnswerList.setAdapter(mAnswerAdapter);
        mUnAnswerList.setAdapter(mUnAnswerAdapter);
        getQuestionList();
    }

    private void setEditorName() {
        if (mQuestionList.size() > 0) {
            et_ratingName.setText(!TextUtils.isEmpty(mQuestionList.get(0).getTopics().getEditor()) ?
                    mQuestionList.get(0).getTopics().getEditor() : "");
        }
    }

    /**
     * 获取已答，未答题目列表
     */
    private void getQuestionList() {
        mAnswerListData.clear();
        mUnAnswerListData.clear();
        //过滤已答题，未答题
        try {
            for (int i = 0; i < mQuestionList.size(); i++) {
                RatingQuestionBean ratingQuestionBean = mQuestionList.get(i);
                Topics topics = ratingQuestionBean.getTopics();
                QuestionListBean questionListBean = new QuestionListBean();
                questionListBean.setQuestionPosition(i);
                String topicType = ratingQuestionBean.getTopics().getTopicType();
                if (topicType.equals("1") || topicType.equals("2")) {
                    if (!TextUtils.isEmpty(ratingQuestionBean.getTopics().getAnswerOptionIds())) {
                        //已答
//                        mAnswerListData.add(questionListBean);
                        Answer answer = new Answer();
                        answer.setProjectId(productInfoId);
                        answer.setId(topics.getId());
                        answer.setAnswerDividingValue(topics.getAnswerDividingValue());
                        answer.setAnswerOptionIds(topics.getAnswerOptionIds());
                        answer.setKid(answer.getKid());
                        answer.setEditor(topics.getEditor());
                        answer.setRemark(topics.getRemark());
                        answer.setYn(topics.getYn());
                        answerOldList.add(answer);
                    }
                } else if (topicType.equals("3")) {
                    if (!TextUtils.isEmpty(ratingQuestionBean.getTopics().getAnswerDividingValue()) &&
                            Integer.parseInt(ratingQuestionBean.getTopics().getAnswerDividingValue()) > 0) {
                        //已答
//                        mAnswerListData.add(questionListBean);
                        Answer answer = new Answer();
                        answer.setProjectId(productInfoId);
                        answer.setId(topics.getId());
                        answer.setAnswerDividingValue(topics.getAnswerDividingValue());
                        answer.setAnswerOptionIds(topics.getAnswerOptionIds());
                        answer.setKid(answer.getKid());
                        answer.setEditor(topics.getEditor());
                        answer.setRemark(topics.getRemark());
                        answer.setYn(topics.getYn());
                        answerOldList.add(answer);
                    }
                }
                if (isAnswer(topics.getId())) {
                    //已答
                    mAnswerListData.add(questionListBean);
                } else {
                    //未答
                    mUnAnswerListData.add(questionListBean);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mAnswerAdapter.notifyDataSetChanged();
        mUnAnswerAdapter.notifyDataSetChanged();
        mRatingAdapter.notifyDataSetChanged();
        setEditorName();
    }

    /**
     * 获取一级标题数据
     */
    private void getFirstElements() {
        if (elementsList != null && elementsList.size() > 0) {
            mOneElementList.clear();
            for (int i = 0; i < elementsList.size(); i++) {
                final Elements elements = elementsList.get(i);
                int fid = elements.getFId();
                if (fid == 0) {
                    mOneElementList.add(elements);
                }
            }
        } else {
            Log.d("@@@", "数据库数据缺失");
        }
        if (null != mFirstClassAdapter) {
            mFirstClassAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 获取二级标题数据
     *
     * @param firstElements
     */
    private void getTwoElements(Elements firstElements) {
        Long firstElementsId = firstElements.getId();
        mTwoElementList.clear();
        mSecondClassAdapter.setCurrentItem(0);
        for (int i = 0; i < elementsList.size(); i++) {
            final Elements elements = elementsList.get(i);
            int fid = elements.getFId();
            if (fid == firstElementsId) {
                mTwoElementList.add(elements);
            }
        }
        if (null != mSecondClassAdapter) {
            mSecondClassAdapter.notifyDataSetChanged();
        }

        // 没有二级要素，展示一级要素对应的问卷信息
        if (mTwoElementList.size() == 0 && topicsList.size() > 0) {
            // 获取要素对应的问卷信息
            mSecondClass.setVisibility(View.GONE);
            mThirdClass.setVisibility(View.GONE);
            mQuestionList.clear();
            getQuestionData(firstElements);
        }
        mRatingAdapter.notifyDataSetChanged();
    }

    private void getThirdElements(Elements twoElements) {
        Long firstElementsId = twoElements.getId();
        mThirdElementList.clear();
        mThirdClassAdapter.setCurrentItem(0);
        for (int i = 0; i < elementsList.size(); i++) {
            final Elements elements = elementsList.get(i);
            int fid = elements.getFId();
            if (fid == firstElementsId) {
                mThirdElementList.add(elements);
            }
        }
        if (null != mThirdClassAdapter) {
            mThirdClassAdapter.notifyDataSetChanged();
        }

        // 没有三级要素，展示二级要素对应的问卷信息
        if (mThirdElementList.size() == 0 && topicsList.size() > 0) {
            // 获取要素对应的问卷信息
            mThirdClass.setVisibility(View.GONE);
            mQuestionList.clear();
            getQuestionData(twoElements);
        } else if (mThirdElementList.size() > 0) {
            mThirdClass.setVisibility(View.VISIBLE);
            getQuestionElements(mThirdElementList.get(0));
        }
        mRatingAdapter.notifyDataSetChanged();
    }

    private void getQuestionElements(Elements twoElements) {
        Long twoElementsId = twoElements.getId();
        if (elementsList != null && elementsList.size() > 0) {
            mQuestionList.clear();
            for (int i = 0; i < elementsList.size(); i++) {
                Elements elements = elementsList.get(i);
                int fid = elements.getFId();
                if (fid == twoElementsId) {
                    getQuestionData(elements);
                }
            }
            // 没有三级要素，展示二级要素对应的问卷信息
            if (mQuestionList.size() == 0) {
                // 获取要素对应的问卷信息
                getQuestionData(twoElements);
            }
        }
        mRatingAdapter.notifyDataSetChanged();
    }

    private void getQuestionData(Elements elements) {
        RatingQuestionBean bean = new RatingQuestionBean();
        bean.setTitleName(elements.getContext());
        bean.setFirst(true);
        String eID = String.valueOf(elements.getId());
        for (int i = 0; i < topicsList.size(); i++) {
            Topics topics = topicsList.get(i);
            String tID = topics.getElementId();
            if (eID.equals(tID)) {
                if (i != 0) {
                    bean = new RatingQuestionBean();
                    bean.setFirst(false);
                }
                bean.setTopics(topics);
                mQuestionList.add(bean);
            }
        }
    }

    private void showQuestionItem(int index, final RatingAdapter.ViewHolder viewHolder, RatingQuestionBean bean) {
        try {
            if (null == bean || null == viewHolder) {
                return;
            }
            Topics topics = bean.getTopics();
            int type = Integer.parseInt(topics.getTopicType());
            final String id = topics.getId();
            final String zhinan = topics.getTopicDescribtion();
            String topic = index + "、" + topics.getTopicName();
            if (bean.isFirst()) {
                if (!TextUtils.isEmpty(bean.getTitleName())) {
                    viewHolder.itemTitle.setText(bean.getTitleName());
                }
                viewHolder.itemTitle.setVisibility(View.VISIBLE);
            } else {
                viewHolder.itemTitle.setVisibility(View.GONE);
            }

            // 1 单选题 2多选题 3打分题
            switch (type) {
                case 1: {
                    viewHolder.mRadio.setVisibility(View.VISIBLE);
                    viewHolder.mCheckboxLayout.setVisibility(View.GONE);
                    viewHolder.mEdit.setVisibility(View.GONE);
                    viewHolder.mEditNA.setVisibility(View.GONE);
                    viewHolder.mCheckNA.setVisibility(View.GONE);
                    viewHolder.mRadioNA.setVisibility(View.VISIBLE);

                    viewHolder.mTitleRadio.setText(topic);
                    viewHolder.mRadioZhiNan.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            // 点击指南操作
                            showZhinanDialog(zhinan);
                        }
                    });
                    viewHolder.mRadioZhengJu.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            //证据操作
                            showZhengjuDialog(id);
                        }
                    });
                    viewHolder.mRadioNA.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Answer answer = findAnswer(id);
                            if (viewHolder.mRadioNA.isChecked()) {
                                answer.setYn("0");
                            } else {
                                answer.setYn("1");
                            }
                        }
                    });

                    String optionObjs = topics.getOptionObjs();
                    JSONArray jsonArray = new JSONArray(optionObjs);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        final JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                        final String answerOptionId = jsonObject.getString("id");
                        RadioButton radioButton = new RadioButton(this);
                        int dimension = (int) (getResources().getDimension(R.dimen.qb_px_10) + 0.5f);//会自动转化为像素值
                        radioButton.setPadding(dimension, 0, 0, 0);
                        radioButton.setText(jsonObject.getString("context"));
                        radioButton.setId(i);
                        Answer answerOld = findAnswer(id);
                        String answeroptid = answerOld.getAnswerOptionIds();
                        if (answerOptionId.equals(answeroptid)) {
                            radioButton.setChecked(true);
                        }


                        radioButton.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                //将选项内容回填bean
                                Answer answer = findAnswer(id);
                                answer.setAnswerOptionIds(answerOptionId);
                                answer.setUpload(0);
                            }
                        });

                        //layoutParams 设置margin值
                        RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT);
                        layoutParams.setMargins(0, 0, 0, 0);
                        viewHolder.mRadioGroup.addView(radioButton, layoutParams);
                    }
                    Answer answer = findAnswer(id);
                    viewHolder.mRadioNA.setChecked(answer.getYn().equals("0"));
                }
                break;
                case 2: {
                    viewHolder.mRadio.setVisibility(View.GONE);
                    viewHolder.mCheckbox.setVisibility(View.VISIBLE);
                    viewHolder.mEdit.setVisibility(View.GONE);
                    viewHolder.mTitleCheckBox.setText(topic);
                    viewHolder.mEditNA.setVisibility(View.GONE);
                    viewHolder.mCheckNA.setVisibility(View.VISIBLE);
                    viewHolder.mRadioNA.setVisibility(View.GONE);
                    viewHolder.mCheckBoxZhiNan.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            // 点击指南操作
                            showZhinanDialog(zhinan);
                        }
                    });
                    viewHolder.mCheckBoxZhengJu.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            showZhengjuDialog(id);
                        }
                    });
                    viewHolder.mCheckNA.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Answer answer = findAnswer(id);
                            if (viewHolder.mCheckNA.isChecked()) {
                                answer.setYn("0");
                            } else {
                                answer.setYn("1");
                            }
                        }
                    });

                    ViewGroup.LayoutParams layoutParams = viewHolder.mCheckboxLayout.getLayoutParams();
                    layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                    layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                    viewHolder.mCheckboxLayout.setLayoutParams(layoutParams);
                    String optionObjsOfCheck = topics.getOptionObjs();
                    JSONArray jsonArrayCheck = new JSONArray(optionObjsOfCheck);
                    final DividingValue dividingValue = new DividingValue();
                    for (int i = 0; i < jsonArrayCheck.length(); i++) {
                        final JSONObject jsonObject = (JSONObject) jsonArrayCheck.get(i);
                        final String answerOptionId = jsonObject.getString("id");
                        CheckBox checkBox = new CheckBox(this);
                        int dimension = (int) (getResources().getDimension(R.dimen.qb_px_10) + 0.5f);//会自动转化为像素值
                        checkBox.setPadding(dimension, 0, 0, 0);
                        checkBox.setText(jsonObject.getString("context"));
                        ViewGroup.LayoutParams checkBoxLayoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT);
                        checkBox.setLayoutParams(checkBoxLayoutParams);
                        final Msg msg = new Msg();
                        Answer answerOld = findAnswer(id);
                        String answeroptid = answerOld.getAnswerOptionIds();
                        if (null != answeroptid && answeroptid.contains(answerOptionId)) {
                            checkBox.setChecked(true);
                            msg.setCheck(true);
                        }

                        checkBox.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (msg.isCheck()) {
                                    msg.setCheck(false);
                                    Answer answer = findAnswer(id);
                                    String newIds = "";
                                    if (null != answer) {
                                        String ids = answer.getAnswerOptionIds();
                                        try {
                                            if (!TextUtils.isEmpty(ids)) {
                                                String[] split = ids.split(",");
                                                for (String string : split) {
                                                    if (!string.equals(jsonObject.getString("id"))) {
                                                        newIds = newIds + string + ",";
                                                    }
                                                }
                                                newIds = newIds.substring(0, newIds.length() - 1);
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                        answer.setAnswerOptionIds(newIds);
                                        answer.setUpload(0);
                                    }

                                } else {
                                    msg.setCheck(true);
                                    dividingValue.setDividingValue(dividingValue.getDividingValue() + jsonObject.optInt("dividingValue"));
                                    //将选项内容回填bean
                                    Answer answer = findAnswer(id);
                                    try {
                                        String ids = answer.getAnswerOptionIds();
                                        if (null != ids) {
                                            ids = answer.getAnswerOptionIds() + "," + jsonObject.getString("id");
                                        } else {
                                            ids = jsonObject.getString("id");
                                        }
                                        answer.setAnswerOptionIds(ids);
                                        answer.setAnswerDividingValue(dividingValue.getDividingValue() + "");
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    answer.setUpload(0);
                                }
                            }
                        });
                        viewHolder.mCheckboxLayout.addView(checkBox);
                    }

                    Answer answer = findAnswer(id);
                    viewHolder.mCheckNA.setChecked(answer.getYn().equals("0"));
                }
                break;
                case 3: {
                    viewHolder.mRadio.setVisibility(View.GONE);
                    viewHolder.mCheckboxLayout.setVisibility(View.GONE);
                    viewHolder.mEdit.setVisibility(View.VISIBLE);
                    viewHolder.mEditNA.setVisibility(View.VISIBLE);
                    viewHolder.mCheckNA.setVisibility(View.GONE);
                    viewHolder.mRadioNA.setVisibility(View.GONE);

                    viewHolder.mTitleEdit.setText(topic);

                    viewHolder.mEditNA.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Answer answer = findAnswer(id);
                            if (viewHolder.mEditNA.isChecked()) {
                                answer.setYn("0");
                            } else {
                                answer.setYn("1");
                            }
                        }
                    });

                    viewHolder.mEditZhiNan.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            showZhinanDialog(zhinan);
                        }
                    });
                    viewHolder.mEditZhengJu.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            showZhengjuDialog(id);
                        }
                    });
                    viewHolder.mEditView.setMaxValue(Integer.parseInt(topics.getTopicMaxScore()));
                    viewHolder.mEditView.setMinValue(Integer.parseInt(topics.getTopicMinScore()));

                    Answer answer = findAnswer(id);
                    String answerDividingValue = answer.getAnswerDividingValue();
                    if (!TextUtils.isEmpty(answerDividingValue)) {
                        try {
                            viewHolder.mEditView.setText(Integer.parseInt(answerDividingValue));
                        } catch (Exception e) {
                        }

                    } else {
                        viewHolder.mEditView.setText(0);
                    }

                    viewHolder.mEditView.setCallback(new IChangeCoutCallback() {
                        @Override
                        public void change(int count) {            //总价变化
                            Answer answer = findAnswer(id);
                            answer.setAnswerDividingValue(String.valueOf(count));
                            answer.setUpload(0);
                            answerList.add(answer);
                            answerOldList.add(answer);
                        }
                    });
                    viewHolder.mEditNA.setChecked(answer.getYn().equals("0"));
                }
                break;
            }
        } catch (Exception e) {

        }
    }

    private Answer findAnswer(String topicId) {
        if (null != answerList && answerList.size() > 0) {
            for (Answer answer : answerList) {
                if (answer.getId().equals(topicId)) {
                    return answer;
                }
            }
        }

        if (null != answerOldList && answerOldList.size() > 0) {
            for (Answer answer : answerOldList) {
                if (answer.getId().equals(topicId)) {
                    Answer newAnswer = new Answer();
                    newAnswer.setProjectId(answer.getProjectId());
                    newAnswer.setId(topicId);
                    newAnswer.setAnswerDividingValue(answer.getAnswerDividingValue());
                    newAnswer.setAnswerOptionIds(answer.getAnswerOptionIds());
                    newAnswer.setKid(answer.getKid());
                    newAnswer.setEditor(answer.getEditor());
                    newAnswer.setQuestionList(answer.getQuestionList());
                    newAnswer.setRemark(answer.getRemark());
                    newAnswer.setYn(answer.getYn());
                    newAnswer.setRemarkUrrl(answer.getRemarkUrrl());
                    newAnswer.setUpload(answer.getUpload());
                    newAnswer.setZhengjuPath(answer.getZhengjuPath());
                    answerList.add(newAnswer);
                    return newAnswer;
                }
            }
        }

        Answer answer = new Answer();
        answer.setProjectId(productInfoId);
        answer.setId(topicId);
        answerList.add(answer);
        answerOldList.add(answer);
        return answer;
    }

    private boolean isAnswer(String currentTopIcId) {
        if (null != answerOldList && answerOldList.size() > 0) {
            for (Answer answer : answerOldList) {
                if (answer.getId().equals(currentTopIcId)) {
                    if (!TextUtils.isEmpty(answer.getAnswerOptionIds()) ||
                            (!TextUtils.isEmpty(answer.getAnswerDividingValue())&&
                                    Integer.parseInt(answer.getAnswerDividingValue()) > 0)) {
                        //已答
                        return true;
                    }else{
                        return false;
                    }
                }
            }
        }
        return false;
    }

//    private void updateOldAnswer(Answer newAnswer, String topicId) {
//        if (null != answerOldList && answerOldList.size() > 0) {
//            for (Answer answer : answerOldList) {
//                if (answer.getId().equals(topicId)) {
//                    answer.setAnswerOptionIds(newAnswer.getAnswerOptionIds());
//                    answer.setAnswerDividingValue(newAnswer.getAnswerDividingValue());
//                    answer.setUpload(0);
//                    answer.setAnswerOptionIds(newAnswer.getAnswerOptionIds());
//                }
//            }
//        }
//    }

    private void showZhengjuDialog(final String topicId) {
        popupLayout = PopupLayout.init(this, R.layout.zhengjulayout);
        popupLayout.setUseRadius(true);
        PopupDialog popupDialog = popupLayout.getPopupDialog();
        popupLayout.show(PopupLayout.POSITION_CENTER);
        try {
            imageGridView = popupDialog.findViewById(R.id.image_list);
            final EditText remarks = popupDialog.findViewById(R.id.editText);
            final Answer answer = findAnswer(topicId);
            remarks.setText(TextUtils.isEmpty(answer.getRemark()) ? "" : answer.getRemark());
            remarks.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    answer.setRemark(remarks.getText().toString());
                }
            });
            getImage(topicId);
            mImageAdapter = new ImageAdapter(this, mImageList);
            imageGridView.setAdapter(mImageAdapter);
            imageGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (mImageList.size() > 9) {
                        Toast.makeText(RatingActivity.this, "最多添加9张", Toast.LENGTH_SHORT).show();
                    }
                    if (position >= mImageList.size()) {
                        String fileName = topicId;
                        startCamera(fileName, topicId);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void getImage(String topicId) {
        Answer answer = findAnswer(topicId);
        mImageList.clear();
        String zhengjuPath = answer.getZhengjuPath();
        if (!TextUtils.isEmpty(zhengjuPath)) {
            String[] split = zhengjuPath.split(",");
            if (null != split && split.length > 0) {
                List<String> strings = Arrays.asList(split);
                mImageList.addAll(strings);
            }
        }
    }

    private void showZhinanDialog(String zhinan) {
        PopupLayout popupLayout = PopupLayout.init(this, R.layout.layout_zhinan);
        popupLayout.setUseRadius(true);
        PopupDialog popupDialog = popupLayout.getPopupDialog();
        popupLayout.show(PopupLayout.POSITION_CENTER);

        TextView textView = popupDialog.findViewById(R.id.tv_zhinan);
        textView.setText(zhinan);
    }


    private void startCamera(String fileName, String topicId) {
        //有权限，直接拍照
        currentTopIcId = topicId;
        currentFileName = fileName;
        if (!EasyPermissions.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            //申请权限，REQUEST_TAKE_PHOTO_PERMISSION是自定义的常量
            EasyPermissions.requestPermissions(this, "拍照需要相机和用户读写文件的权限", REQUEST_TAKE_PHOTO_PERMISSION,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA);
        } else {
            //有权限，直接拍照
            takePhoto();
        }
    }

    //拍照的代码
    private void takePhoto() {
        try {
            //创建一个File
            photoFile = FileUtil.INSTANCE.createCameraFile(currentFileName);
            Intent openCameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); //系统常量， 启动相机的关键
            startActivityForResult(openCameraIntent, REQUEST_CAMERA);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    class Msg {
        private boolean isCheck;

        Msg() {
        }

        boolean isCheck() {
            return isCheck;
        }

        void setCheck(boolean check) {
            isCheck = check;
        }
    }

    class DividingValue {
        int getDividingValue() {
            return mDividingValue;
        }

        void setDividingValue(int dividingValue) {
            mDividingValue = dividingValue;
        }

        private int mDividingValue = 0;

        DividingValue() {
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CAMERA) {
                if (data != null && data.getExtras() != null) {
                    Bitmap bitmap = data.getExtras().getParcelable("data");
                    saveFile(bitmap);
                }
            }
        }
    }

    public void saveFile(Bitmap bm) {
        try {
            if (null == photoFile) {
                photoFile = FileUtil.INSTANCE.createCameraFile(currentFileName);
            }
            if (!photoFile.exists()) {
                photoFile.createNewFile();
            }
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(photoFile));
            bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
            bos.flush();
            bos.close();
            Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
            Answer answer = findAnswer(currentTopIcId);
            if (TextUtils.isEmpty(answer.getZhengjuPath())) {
                answer.setZhengjuPath(photoFile.getAbsolutePath());
            } else {
                answer.setZhengjuPath(answer.getZhengjuPath() + "," + photoFile.getAbsolutePath());
            }
            answer.setUpload(0);
            if (popupLayout != null) {
                popupLayout.dismiss();
            }
            showZhengjuDialog(currentTopIcId);
        } catch (Exception e) {
            Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        if (requestCode == REQUEST_TAKE_PHOTO_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //申请成功，可以拍照
                takePhoto();
            } else {
                Toast.makeText(this, "CAMERA PERMISSION DENIED", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ToastUtil.showLongToast(this, "用户授权失败！");
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        answerOldList.clear();
        answerList.clear();
    }
}


